﻿using Eps.Ai.Common;
using InfonavaEye.common;
using InfonavaEye.components;
using InfonavaEye.model;
using InfonavaEye.util;
using Newtonsoft.Json;
using Sylan.Common.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media;
using Color = System.Drawing.Color;
using Pen = System.Drawing.Pen;

namespace InfonavaEye.Forms
{
    public partial class BoxModelForm : Form
    {
        public string boxModelName;

        public BoxModel boxModel;

        /// <summary>
        /// 模式， 2 编辑，1 添加,0 查看,3 空
        /// </summary>
        private int mode = 3;

        private string DEFAULT_TEMPLATE_ITEM = "请选择钉盒模板";

        public BoxModelForm()
        {
            InitializeComponent();
        }

        private void BoxModelForm_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;

            this.btnSure.Visible = false;
            this.btnEdit.Visible = true;
            this.btnAdd.Visible = true;
            this.btnDelete.Visible = false;

            this.resetForm(3);
        }

        private void previewPicBox_Paint(object sender, PaintEventArgs e)
        {
            /*var g = e.Graphics;
            GraphicsHelper.SetGDIHigh(g);
            Color bgColor = Color.FromArgb(255, 233, 233, 233);
            GraphicsHelper.FillRoundRectangle(e.ClipRectangle, g, 15, bgColor);*/
        }


        private void loadTemplateList()
        {
            this.cmbTemplate.Items.Clear();
            this.cmbTemplate.Items.Add(DEFAULT_TEMPLATE_ITEM);
            var baseDir = util.FileHelper.getBaseDir();
            DirectoryInfo TheFolder = new DirectoryInfo(baseDir + "\\BoxModel");
            List<FileInfo> filelist = TheFolder.GetFiles().OrderByDescending(fi => fi.LastWriteTime).ToList();
            foreach (FileInfo file in filelist)
            {
                //只显示正常的模板（非正常的为删除的模板）
                if (file.Name.EndsWith(".json"))
                {
                    string itemText = file.Name.Replace(".json", "");
                    this.cmbTemplate.Items.Add(itemText);
                }
            }
        }

        private void cmbTemplate_SelectedIndexChanged(object sender, EventArgs e)
        {
            templateSelectedIndexChanged();
        }

        private void templateSelectedIndexChanged(bool isFirst = false)
        {
            try
            {
                var item = this.cmbTemplate.SelectedItem;
                this.boxModelName = item.ToString();
                if (this.boxModelName.Equals(DEFAULT_TEMPLATE_ITEM))
                {
                    this.resetForm(3);
                }
                else
                {
                    this.mode = 2;
                    this.modeChange();

                    this.boxModel = BoxModelHelper.parseBoxModel(boxModelName);
                    this.txtBoxName.Text = this.boxModel.boxName;
                    this.setShape();
                    this.renderAreaList();
                    ThreadHelper.ExcuteThreadTask(() =>
                    {
                        this.drawAreas();
                    }, 100);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 绘制区域列表
        /// </summary>
        private void renderAreaList()
        {

            panelArea.Controls.Clear();
            int areaCount = 0;
            int areaHeight = 80;
            int areaMarginLeft = 24;
            int areaMarginTop = 12;
            if (this.boxModel != null && this.boxModel.boxAreas != null)
            {
                areaCount = this.boxModel.boxAreas.Count;
                int index = 0;
                this.boxModel.boxAreas.ForEach(area =>
                {
                    var panel3 = new System.Windows.Forms.Panel();
                    var label6 = new System.Windows.Forms.Label();
                    var pictureBox1 = new System.Windows.Forms.PictureBox();
                    var label5 = new System.Windows.Forms.Label();
                    //var label4 = new System.Windows.Forms.Label();
                    var btnRemoveArea = new System.Windows.Forms.Button();
                    panel3.SuspendLayout();

                    // 
                    // label6 -行 x  列
                    // 
                    label6.AutoSize = true;
                    label6.Font = new System.Drawing.Font("宋体", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                    label6.Location = new System.Drawing.Point(440, 28);
                    label6.Name = "label6";
                    label6.Size = new System.Drawing.Size(59, 20);
                    label6.TabIndex = 3;
                    label6.Text = String.Format("{0} x {1}", area.rowCount, area.columnCount);
                    // 
                    // pictureBox1
                    // 
                    pictureBox1.Image = global::InfonavaEye.Properties.Resources.nail_empty;
                    pictureBox1.Location = new System.Drawing.Point(401, 19);
                    pictureBox1.Name = "pictureBox1";
                    pictureBox1.Size = new System.Drawing.Size(33, 40);
                    pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
                    pictureBox1.TabIndex = 2;
                    pictureBox1.TabStop = false;
                    // 
                    // label5
                    // 
                    label5.AutoSize = true;
                    label5.Font = new System.Drawing.Font("黑体", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                    label5.Location = new System.Drawing.Point(3, 28);
                    label5.Name = "label5";
                    label5.Size = new System.Drawing.Size(69, 19);
                    label5.TabIndex = 1;
                    label5.Text = area.name;
                    /*// 
                    // label4
                    // 
                    label4.AutoSize = true;
                    label4.Font = new System.Drawing.Font("黑体", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                    label4.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(55)))), ((int)(((byte)(55)))), ((int)(((byte)(55)))));
                    label4.Location = new System.Drawing.Point(12, 16);
                    label4.Name = "label4";
                    label4.Size = new System.Drawing.Size(69, 20);
                    label4.TabIndex = 0;
                    label4.Text = area.code;*/

                    // 
                    // btnRemoveArea
                    // 
                    btnRemoveArea.BackColor = System.Drawing.Color.White;
                    btnRemoveArea.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(77)))), ((int)(((byte)(203)))));
                    btnRemoveArea.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
                    btnRemoveArea.Font = new System.Drawing.Font("黑体", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                    btnRemoveArea.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(77)))), ((int)(((byte)(203)))));
                    btnRemoveArea.Location = new System.Drawing.Point(535, 16);
                    btnRemoveArea.Name = "btnRemoveArea";
                    btnRemoveArea.Size = new System.Drawing.Size(60, 44);
                    btnRemoveArea.TabIndex = 33;
                    btnRemoveArea.Text = "删除";
                    btnRemoveArea.UseVisualStyleBackColor = false;
                    btnRemoveArea.Click += new System.EventHandler(this.btnRemoveArea_Click);

                    // 
                    // panel3
                    // 
                    panel3.Controls.Add(label6);
                    panel3.Controls.Add(pictureBox1);
                    panel3.Controls.Add(label5);
                    //panel3.Controls.Add(label4);
                    panel3.Controls.Add(btnRemoveArea);
                    panel3.BorderStyle = System.Windows.Forms.BorderStyle.None;
                    panel3.Location = new System.Drawing.Point(areaMarginLeft, (areaHeight + areaMarginTop) * (index) + areaMarginTop);
                    panel3.Name = "panel3";
                    panel3.Size = new System.Drawing.Size(607, areaHeight);
                    panel3.TabIndex = 0;
                    panel3.Tag = index;
                    panel3.Click += new System.EventHandler(this.areaItem_Click);
                    panel3.Paint += new System.Windows.Forms.PaintEventHandler(this.areaItem_Paint);

                    //给每个区域项 增加点击事件
                    for (int i = 0, count = panel3.Controls.Count; i < count; i++)
                    {
                        panel3.Controls[i].Tag = index;
                        if (!(panel3.Controls[i] is Button))
                        {
                            panel3.Controls[i].Click += new System.EventHandler(this.areaItem_Click);
                        }
                    }

                    panelArea.Controls.Add(panel3);
                    index++;
                });
            }

            #region 添加按钮
            var panelAddArea = new System.Windows.Forms.Panel();
            var picPlus = new System.Windows.Forms.PictureBox();
            var label7 = new Label();
            panelAddArea.SuspendLayout();
            // 
            // label7
            // 
            label7.AutoSize = true;
            label7.Font = new System.Drawing.Font("黑体", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            label7.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(55)))), ((int)(((byte)(55)))), ((int)(((byte)(55)))));
            label7.Location = new System.Drawing.Point(260, 22);
            label7.Name = "label7";
            label7.Size = new System.Drawing.Size(89, 20);
            label7.TabIndex = 0;
            label7.Text = "添加区域";
            label7.Click += new System.EventHandler(this.panelAddArea_Click);
            // 
            // picPlus
            // 
            picPlus.BackgroundImage = global::InfonavaEye.Properties.Resources.plus_gray_32;
            picPlus.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
            picPlus.Location = new System.Drawing.Point(219, 21);
            picPlus.Name = "picPlus";
            picPlus.Size = new System.Drawing.Size(26, 24);
            picPlus.TabIndex = 1;
            picPlus.TabStop = false;
            // 
            // panelAddArea
            // 
            panelAddArea.BorderStyle = System.Windows.Forms.BorderStyle.None;
            panelAddArea.Controls.Add(picPlus);
            panelAddArea.Controls.Add(label7);
            panelAddArea.Location = new System.Drawing.Point(areaMarginLeft, (areaHeight + areaMarginTop) * (areaCount) + areaMarginTop);
            panelAddArea.Name = "panelAddArea";
            panelAddArea.Size = new System.Drawing.Size(607, 65);
            panelAddArea.TabIndex = 1;
            panelAddArea.Margin = new Padding(3, 3, 3, 23);
            panelAddArea.Click += new System.EventHandler(this.panelAddArea_Click);
            panelAddArea.Paint += new System.Windows.Forms.PaintEventHandler(this.areaItem_Paint);
            panelAddArea.ResumeLayout(false);
            panelAddArea.PerformLayout();
            this.panelArea.Controls.Add(panelAddArea);
            this.panelArea.ResumeLayout(true);
            this.panelArea.PerformLayout();
            #endregion
        }

        bool isClick = false;
        /// <summary>
        /// 点击 区域列表中的项，弹出修改区域页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void areaItem_Click(object sender, EventArgs e)
        {
            if (isClick) return;
            isClick = true;
            try
            {
                Control control = sender as Control;
                var itemIndex = (int)control.Tag;

                //弹出修改区域页
                BoxAreaForm form = new BoxAreaForm();
                form.Mode = this.mode;
                form.BoxModel = this.boxModel;
                form.boxAngle = this.boxModel.boxAngle;
                form.BoxArea = this.boxModel.boxAreas[itemIndex];
                if (form.ShowDialog() == DialogResult.OK)
                {
                    //更新数据
                    this.boxModel.boxAngle = form.boxAngle;
                    this.boxModel.boxAreas[itemIndex] = form.BoxArea;
                    this.renderAreaList();
                    this.drawAreas();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0}，{1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                isClick = false;
            }
        }

        Color mainColor = Color.FromArgb(255, 180, 180, 180);
        int margin = 600;
        int paddingTop = 900;
        int paddingBottom = 300;
        int paddingH = 500;
        int nailWidth = 400;
        int nailHeight = 400;
        float scaleRate = 1 / 24f;
        public List<Nail> nailList = new List<Nail>();
        Graphics drawG = null;

        private void drawAreas()
        {
            if (drawG == null)
            {
                drawG = previewPicBox.CreateGraphics();
                GraphicsHelper.SetGDIHigh(drawG);
            }
            Color areaColor = Color.FromArgb(255, 250, 250, 250);
            Color bgColor = Color.FromArgb(255, 233, 233, 233);
            GraphicsHelper.FillRoundRectangle(previewPicBox.ClientRectangle, drawG, 15, bgColor);

            if (this.boxModel == null || this.boxModel.boxAreas == null || this.boxModel.boxAreas.Count == 0) return;
            //selectedNailCount = 0;
            nailList.Clear();
            int minX = (this.boxModel.boxAreas.Min(p => p.startPoint[0]));
            int minY = (this.boxModel.boxAreas.Min(p => p.startPoint[1]));
            int maxX = (this.boxModel.boxAreas.Max(p => p.startPoint[0]));
            int maxY = (this.boxModel.boxAreas.Max(p => p.startPoint[1]));
            int maxWidth = maxX - minX;
            int maxHeight = maxY - minY;
            int fixX = 0 - minX;
            int fixY = 0 - minY;

            this.boxModel.boxAreas.ForEach((area) =>
            {
                try
                {
                    Console.WriteLine("绘制区域:" + area.name);
                    var startPoint = area.startPoint;
                    var columnTitles = area.columnTitle;

                    //画外框
                    var x = startPoint[0] + fixX + margin;
                    var y = startPoint[1] + fixY + margin;
                    var width = area.holdPitch[0] * (area.columnCount - 1) + 2 * (paddingH);
                    var height = area.holdPitch[1] * (area.rowCount - 1) + (paddingTop + paddingBottom);
                    var newPoint = flipXY((int)(x * scaleRate), (int)(y * scaleRate));
                    Console.WriteLine("绘制区域参数：x {0}，y {1},width {2},height {3}", x * scaleRate, y * scaleRate, width * scaleRate, height * scaleRate);
                    var areaPath = GraphicsHelper.DrawRoundRect((int)newPoint.X - (int)(width * scaleRate), (int)newPoint.Y - (int)(height * scaleRate), (int)(width * scaleRate), (int)(height * scaleRate), 15);
                    drawG.DrawPath(new Pen(areaColor, 1), areaPath);
                    //画螺钉
                    for (int i = 0; i < area.columnCount; i++)
                    {
                        for (int j = 0; j < area.rowCount; j++)
                        {
                            width = nailWidth;
                            height = nailHeight;
                            /*if (i == 0 && j == 0)
                            {
                                width = (int)Math.Round(nailWidth * 1.5, 0);
                                height = (int)Math.Round(nailWidth * 1.5, 0);
                            }*/

                            x = startPoint[0] + fixX + area.holdPitch[0] * i + paddingH + margin - (width) / 2;
                            y = startPoint[1] + fixY + area.holdPitch[1] * j + paddingTop + margin - (height) / 2;

                            newPoint = flipXY((int)(x * scaleRate), (int)(y * scaleRate));
                            Rectangle r = new Rectangle((int)newPoint.X - (int)(width * scaleRate), (int)newPoint.Y - (int)(height * scaleRate), (int)(width * scaleRate), (int)(height * scaleRate));

                            //var nailKey = string.Format(AutoStartParams.NAIL_MAP_KEY_FORMAT, area.name, i, j);

                            nailList.Add(new Nail()
                            {
                                area = area,
                                point = new Point(i, j),
                                location = r,
                                updateTime = DateTime.Now,
                            });
                            //Console.WriteLine("绘制钉子 ({0})：x {1}，y {2},width {3},height {4}", i + ":" + j, x * scaleRate, y * scaleRate, width * scaleRate, height * scaleRate);
                            drawG.DrawImage(Properties.Resources.nail_empty, r);

                            //第一排头部写上数字
                            if (j == 0 && (columnTitles.Count() - 1) >= i)
                            {
                                drawText(drawG, r, columnTitles[i]);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("绘制区域发生异常：{0}，{1}", ex.Message, ex.StackTrace);
                }
            });
            //previewPicBox.Refresh();
        }

        /// <summary>
        /// 翻转X轴坐标
        /// （使图像本来显示在左侧的，现在显示到右侧）
        /// </summary>
        private System.Windows.Point flipXY(int x, int y)
        {
            int centerX = previewPicBox.Width / 2;
            int centerY = previewPicBox.Height / 2;
            var transform = new RotateTransform() { Angle = 180, CenterX = centerX, CenterY = centerY };
            return transform.Transform(new System.Windows.Point(x, y));
        }

        private void drawText(Graphics graphics, Rectangle nailRect, string text)
        {
            var enlargeWidth = 40;
            var enlargeHeight = 10;
            Rectangle textRect = new Rectangle(nailRect.X - enlargeWidth / 2, nailRect.Y + 25 - enlargeHeight / 2, nailRect.Width + enlargeWidth, nailRect.Height + enlargeHeight);
            Font LabelFont = new Font("黑体", 12, FontStyle.Regular); //设置字体、字号、是否加粗
            SolidBrush labelColor = new SolidBrush(Color.FromArgb(255, 99, 99, 99));//设置字体颜色
            StringFormat sf = new StringFormat();//位置对象
            sf.Alignment = StringAlignment.Center;//居中
            graphics.DrawString(text, LabelFont, labelColor, textRect, sf);
        }

        private void panelBox_Paint(object sender, PaintEventArgs e)
        {
            var react = e.ClipRectangle;
            Color bgColor = Color.FromArgb(255, 0, 77, 203);
            var areaPath = GraphicsHelper.DrawRoundRect(react.X, react.Y, react.Width - 5, react.Height - 5, 15);
            var g = e.Graphics;
            GraphicsHelper.SetGDIHigh(g);
            //g.Clear(panelBox.BackColor);
            g.DrawPath(new Pen(bgColor, 1), areaPath);

        }

        private void panelArea_Paint(object sender, PaintEventArgs e)
        {
            /* var react = e.ClipRectangle;
             Color bgColor = Color.FromArgb(255, 240, 240, 240);
             var areaPath = GraphicsHelper.DrawRoundRect(react.X, react.Y, react.Width - 5, react.Height - 5, 15);
             var g = e.Graphics;
             GraphicsHelper.SetGDIHigh(g);
             //g.Clear(panelBox.BackColor);
             g.DrawPath(new Pen(bgColor, 1), areaPath);*/
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            if (this.mode == 3)
            {
                this.Close();
            }
            else
            {
                this.resetForm(3);
            }
        }

        private void panelAddArea_Click(object sender, EventArgs e)
        {
            if (isClick) return;
            isClick = true;
            try
            {
                BoxAreaForm form = new BoxAreaForm();
                form.Mode = 1;
                if (form.ShowDialog() == DialogResult.OK)
                {
                    this.boxModel.boxAngle = form.boxAngle;
                    this.boxModel.boxAreas.Add(form.BoxArea);
                    this.renderAreaList();
                    this.drawAreas();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0}，{1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                isClick = false;
            }
        }

        private void btnSure_Click(object sender, EventArgs e)
        {
            if (!checkForm()) return;

            string fileName;
            if (this.mode == 1)
            {
                fileName = this.txtBoxName.Text;
            }
            else
            {
                //编辑模式下 自动增加版本号
                fileName = this.boxModelName;
                Regex regex = new Regex("@(\\d+)", RegexOptions.IgnoreCase);
                var regResult = regex.Match(fileName);
                int version = 1;
                if (regResult.Success)
                {
                    version = int.Parse(regResult.Groups[1].Value);//文件版本号
                    version++;
                    fileName = fileName.Replace("@" + (version - 1), "@" + version);
                }
                else
                {
                    fileName = fileName + "@1";
                }
            }

            fileName = Regex.Replace(fileName, "(\\s+)", "_", RegexOptions.None);
            var boxModelStr = JsonConvert.SerializeObject(this.boxModel);
            var baseDir = util.FileHelper.getBaseDir();
            var modelDir = Path.Combine(baseDir, "BoxModel");
            var fullPath = Path.Combine(modelDir, fileName + ".json");
            if (this.mode == 1 && File.Exists(fullPath))
            {
                AutoCloseMessageBox.Show("已经存在这个名字的模板，请修改模板名称再尝试");
                return;
            }

            try
            {
                util.FileHelper.saveFile(boxModelStr, fullPath);
                AutoCloseMessageBox.Show(String.Format("最新的模板已保存为:【{0}】,请选择最新的模板来查看", fileName));
                this.loadTemplateList();
                this.resetForm(3);
            }
            catch (Exception ex)
            {
                Console.WriteLine("保存模板失败，{0} {1}", ex.Message, ex.StackTrace);
                AutoCloseMessageBox.Show("保存模板失败，{0}", ex.Message);
            }
        }

        private bool checkForm()
        {
            //编辑模式下 必须要选择1个模板
            if (this.mode == 2 && this.cmbTemplate.SelectedIndex < 0)
            {
                AutoCloseMessageBox.Show("请先选择一个模板再编辑");
                return false;
            }

            if (String.IsNullOrEmpty(this.txtBoxName.Text))
            {
                AutoCloseMessageBox.Show("请输入模板名称");
                return false;
            }
            else
            {
                this.boxModel.boxName = this.txtBoxName.Text.Trim();
            }

            int shape = getShape();
            if (shape==4)
            {
                AutoCloseMessageBox.Show("请选择钉子形状");
                return false;
            }
            else
            {
                this.boxModel.NailShape = shape;
            }

            if (this.boxModel == null || this.boxModel.boxAreas == null || this.boxModel.boxAreas.Count == 0)
            {
                AutoCloseMessageBox.Show("模板至少应添加1个区域");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 获取选择的钉子形状
        /// </summary>
        /// <returns></returns>
        private int getShape() {
            if (this.radioShape1.Checked)
            {
                return 1;
            }
            else if (this.radioShape2.Checked)
            {
                return 2;
            }
            else {
                return 4;
            }
        }

        private void setShape() {
            this.radioShape1.Checked = (this.boxModel.NailShape == 1);
            this.radioShape2.Checked = (this.boxModel.NailShape == 2);
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            this.resetForm(1);
        }

        /// <summary>
        /// 重置界面为新增状态
        /// (模式， 2 编辑，1 添加,0 查看,3 空)
        /// </summary>
        private void resetForm(int mode)
        {
            this.mode = mode;
            if (mode == 1)
            {
                //添加模式
                this.modeChange();
                this.boxModel = new BoxModel()
                {
                    boxCode = Guid.NewGuid().ToString("N"),
                    boxAreas = new List<BoxArea>()
                };
                this.renderAreaList();
                this.drawAreas();
            }
            else if (mode == 2)
            {
                //编辑模式
                this.loadTemplateList();
                this.modeChange();
            }
            else if (mode == 0)
            {
                //查看模式
                this.modeChange();

                //默认选中第一个模板
                if (this.cmbTemplate.Items.Count > 0)
                {
                    this.cmbTemplate.SelectedIndex = 0;
                }
            }
            else if (mode == 3)
            {
                //空模式
                this.loadTemplateList();
                this.cmbTemplate.SelectedIndexChanged -= new System.EventHandler(this.cmbTemplate_SelectedIndexChanged);
                //默认选中第一个模板
                if (this.cmbTemplate.Items.Count > 0)
                {
                    this.cmbTemplate.SelectedIndex = 0;
                    //this.templateSelectedIndexChanged(true);
                    this.cmbTemplate.SelectedIndexChanged += new System.EventHandler(this.cmbTemplate_SelectedIndexChanged);
                }
                this.modeChange();
                panelArea.Controls.Clear();
                this.boxModel = null;
                this.drawAreas();
            }
        }

        private void modeChange()
        {
            if (this.mode == 1)
            {
                //添加模式
                this.panelSelectTemplate.Visible = false;
                this.btnSure.Visible = true;
                this.btnEdit.Visible = false;
                this.btnAdd.Visible = false;
                this.btnDelete.Visible = false;
                this.txtBoxName.Text = String.Empty;
                this.txtBoxName.Enabled = true;
                this.btnSure.Text = "添加";
                this.btnBack.Text = "取消";
            }
            else if (this.mode == 2)
            {
                //编辑模式
                this.panelSelectTemplate.Visible = false;
                this.btnSure.Visible = true;
                this.btnEdit.Visible = false;
                this.btnDelete.Visible = true;
                this.btnAdd.Visible = false;
                this.txtBoxName.Enabled = true;
                this.btnSure.Text = "保存";
                this.btnBack.Text = "取消";
            }
            else if (this.mode == 0)
            {
                //查看模式
                this.panelSelectTemplate.Visible = true;
                this.btnSure.Visible = false;
                this.btnEdit.Visible = true;
                this.btnAdd.Visible = true;
                this.btnDelete.Visible = true;
                this.txtBoxName.Enabled = false;
                this.btnBack.Text = "返回";
            }
            else if (this.mode == 3)
            {
                //空模式
                this.panelSelectTemplate.Visible = true;
                this.btnSure.Visible = false;
                this.btnEdit.Visible = true;
                this.btnAdd.Visible = true;
                this.btnDelete.Visible = false;
                this.txtBoxName.Enabled = false;
                this.btnBack.Text = "返回";
                txtBoxName.Text = "";
            }
        }

        /// <summary>
        /// 删除某个区域
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRemoveArea_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定删除吗？", "提示", MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
            {
                Control btn = (Control)sender;
                this.boxModel.boxAreas.RemoveAt((int)btn.Tag);
                this.renderAreaList();
                this.drawAreas();
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(String.Format("确定要删除模板【{0}】吗？删除了无法恢复哦~", this.boxModelName), "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    string path = Path.Combine(util.FileHelper.getBaseDir() + "\\BoxModel", this.boxModelName + ".json");
                    string deletePath = path + ".delete";
                    File.Move(path, deletePath);
                    this.loadTemplateList();
                    this.resetForm(3);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("删除模板失败，{0} {1}", ex.Message, ex.StackTrace);
                    AutoCloseMessageBox.Show("删除模板失败，{0}", ex.Message);
                }
            }
        }

        private void areaItem_Paint(object sender, PaintEventArgs e)
        {
            Control p = (Control)sender;
            Pen pp = new Pen(Color.FromArgb(255, 0, 77, 203));
            e.Graphics.DrawRectangle(pp, e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.X + e.ClipRectangle.Width - 1, e.ClipRectangle.Y + e.ClipRectangle.Height - 1);
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (DEFAULT_TEMPLATE_ITEM.Equals(this.cmbTemplate.SelectedItem))
            {
                AutoCloseMessageBox.Show("请选择钉盒模板");
            }
            else
            {
                this.resetForm(2);
            }
        }

        private void txtSpeedX_KeyPress(object sender, KeyPressEventArgs e)
        {
            //如果输入的不是退格和数字，则屏蔽输入
            if (!(e.KeyChar == 8 || (e.KeyChar >= 48 && e.KeyChar <= 57)))
            {
                e.Handled = true;
            }
        }

        private void txtSpeedY_KeyPress(object sender, KeyPressEventArgs e)
        {
            //如果输入的不是退格和数字，则屏蔽输入
            if (!(e.KeyChar == 8 || (e.KeyChar >= 48 && e.KeyChar <= 57)))
            {
                e.Handled = true;
            }
        }
       
        private void radioShape1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void radioShape2_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void radioShape3_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
